from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class EmailBackend(ModelBackend):
    """
    自定义认证后端，允许使用用户名或邮箱进行认证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            # 尝试通过用户名查找用户
            user = UserModel.objects.get(username=username)
            if user.check_password(password) and user.is_active:
                return user
        except UserModel.DoesNotExist:
            # 如果通过用户名找不到，尝试通过邮箱查找
            try:
                user = UserModel.objects.get(email=username)
                if user.check_password(password) and user.is_active:
                    return user
            except UserModel.DoesNotExist:
                return None

    def get_user(self, user_id):
        UserModel = get_user_model()
        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
